import os, sys
APPLICATION_INSTALL_DIR = os.environ.get('SIMPLEAUTH_INSTALL')
if not APPLICATION_INSTALL_DIR:
    raise EnvironmentError("Must Set SIMPLEAUTH_INSTALL in the environment!")

sys.path.append(os.path.join(APPLICATION_INSTALL_DIR, "lib%spython" % os.sep))

from simple_auth.config import DEFAULT_CONFIG_PATH, ConfigLoader


class UnsupportedEnvError(Exception):
    """simply indicates that an attempted config is not valid"""

class EnvironmentBuilder(object):
    def __init__(self, configName=None, configPath=None):
        if configPath is None:
            configPath = DEFAULT_CONFIG_PATH
        appConfig = ConfigLoader(configPath).load('app')
        if not configName:
            configName = str(appConfig.environment)
        env_name = "environ_" + configName
        try:
            self.config = ConfigLoader(configPath).load(env_name)
        except:
            try:
                possibleConfig = os.path.join(os.path.dirname(__file__), "conf")
                self.config = ConfigLoader(possibleConfig).load(server_name)
            except:
                raise
        try:
            db = self.config.xml_xpath("db[@name='simple_auth']")[0]
            self.simple_dbtype = str(db.type)
            self.simple_dburi = str(db.uri)
        except IndexError:
            self.simple_dbtype = None
            self.simple_dburi = None
        self.default_server = str(self.config.svc.default_server.name)
        self.default_port = str(self.config.svc.default_server.listen_port)
